package tms.controler;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import javax.swing.JOptionPane;
import javax.swing.JTable;

import tms.model.Account;
import tms.model.Booking;
import tms.model.Destination;
import tms.model.Flight;
import tms.service.ServiceHandler;
import tms.view.ConfirmView;
import tms.view.ContactInfoView;

public class ConfirmController implements IController {

    private ConfirmView view;

    private SummaryController bsc;

    private String ticNumDep;
    private String ticNumRe;

    private String[] columnNames = {"Description", "Amount", "VAT", "Total"};

    public ConfirmController(SummaryController bsc) {
        this.bsc = bsc;
    }

    public void getFlightFromBooking() {
        Booking depTicket = bsc.getDepatureTicket();
        Booking returnTicket = bsc.getReturnTicket();

        Flight depFlight = depTicket.getFlight();

        Destination desDepDepFlight = depFlight.getDeparting();
        Destination desArrDepFlight = depFlight.getArriving();
        String depDepFlight = depFlight.getDepHour() + ":" +
                depFlight.getDepMinute() + " (" + desDepDepFlight.getDestCode();
        depDepFlight += ") " + desDepDepFlight.getDestName();
        String arrDepFlight =  "(" + desArrDepFlight.getDestCode();
        arrDepFlight += ")\n " + desArrDepFlight.getDestName();
        String depFlightDetail = depFlight.getFlightName();

        ticNumDep = "TK" + rdInt(1000, 9999);
        view.setDepDepFlight(depDepFlight);
        view.setArriDepFlight(arrDepFlight);
        view.setDetailDepFlight(depFlightDetail);
        String ticketNumber = ticNumDep;

        if (returnTicket != null) {
            Flight returnFlight = returnTicket.getFlight();
            Destination desDepReFlight = returnFlight.getDeparting();
            Destination desArrReFlight = returnFlight.getArriving();

            String depReFlight = returnFlight.getDepHour() + ":" +
                    returnFlight.getDepMinute() + " (" + desDepReFlight.getDestCode();
            depReFlight += ") " + desDepReFlight.getDestName();
            String arrReFlight = "(" + desArrReFlight.getDestCode();
            arrReFlight += ") " + desArrReFlight.getDestName();
            String reFlightDetail = returnFlight.getFlightName();
            ticNumRe = "TK" + rdInt(1000, 9999);
            ticketNumber += "(depature ticket) & " + ticNumRe + "(return ticket)";
            view.setDepReFlightt(depReFlight);
            view.setArriReFlight(arrReFlight);
            view.setDetailReFlight(reFlightDetail);
        }
        view.setTicketNumber(ticketNumber);
    }

    public void getPassengerInformation() {
        Booking depTicket = bsc.getDepatureTicket();
        Account passengerAccount = depTicket.getBookingAccount();
        if (passengerAccount != null) {
            view.setTitlePass(passengerAccount.getTitle());
            view.setfName(passengerAccount.getFirstName());
            view.setlName(passengerAccount.getLastName());
            view.setMobile(passengerAccount.getPhone());
            view.setEmail(passengerAccount.getEmail());
            view.setCountry(passengerAccount.getCountry());
            view.setAdd(passengerAccount.getAddress());
            view.setDOB(passengerAccount.getBirthDate());
        } else {
            Account guest = ContactInfoView.getGuest();
            view.setTitlePass(guest.getTitle());
            view.setfName(guest.getFirstName());
            view.setlName(guest.getLastName());
            view.setMobile(guest.getPhone());
            view.setEmail(guest.getEmail());
            view.setCountry(guest.getCountry());
            view.setAdd(guest.getAddress());
            view.setDOB(guest.getBirthDate());
        }

        String bookerName = depTicket.getBookingPersonName();
        if (!bookerName.isEmpty()) {
            view.setVisibleBooker(true);
            view.setEmailN2(depTicket.getBookingPersonEmail());
            view.setNameN2(depTicket.getBookingPersonName());
            view.setMobileN2(depTicket.getBookingPersonPhone());
        } else {
            view.setVisibleBooker(false);
        }


    }

    public JTable loadData() {
        //get 2 ticket from Booking
        Booking depTicket = bsc.getDepatureTicket();
        Booking returnTicket = bsc.getReturnTicket();
        List<Booking> lsTicket = new ArrayList<Booking>();
        lsTicket.add(depTicket);
        if (returnTicket != null) {
            lsTicket.add(returnTicket);
        }
        lsTicket.add(null);
        double vat, amount, total = 0.0, sum, tmp1, tmp2, tmp3;
        //String tmp1,tmp2;
        Object[][] data = new Object[lsTicket.size()][columnNames.length];
        for (int i = 0; i < lsTicket.size() - 1; i++) {
            data[i][0] = lsTicket.get(i).getTicketClass();

            amount = lsTicket.get(i).getTotalAmount();
            tmp1 = amount;

            data[i][1] = Double.toString(tmp1) + "$";

            vat = amount / 10.0;
            tmp2 = vat;
            data[i][2] =  Double.toString(tmp2) + "$";

            sum = amount + vat;
            tmp3 = sum;
            data[i][3] = Double.toString(tmp3) + "$";
            total += sum;
        }

        data[lsTicket.size() - 1][0] = "Total";
        data[lsTicket.size() - 1][1] = "";
        data[lsTicket.size() - 1][2] = "";
        data[lsTicket.size() - 1][3] = Double.toString(total) + "$";

        JTable table = new JTable(data, columnNames);
        table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);

        return table;
    }

    /**
     * Save booked ticket into the database.
     * @return
     */
    public boolean insertDB() {
        boolean result = true;
        Booking depTicket = bsc.getDepatureTicket();
        depTicket.setBookingDate(Calendar.getInstance().getTime());
        Booking returnTicket = bsc.getReturnTicket();
        depTicket.setTicketNumber(getTicNumdep());

        if (!ServiceHandler.saveBooking(depTicket)) {
            result = false;
        }

        if (returnTicket != null) {
        	returnTicket.setBookingDate(Calendar.getInstance().getTime());
            returnTicket.setTicketNumber(getTicNumRe());
            if (!ServiceHandler.saveBooking(returnTicket)) {
                result = false;
            }
        }

        return result;
    }

    /**
     * Store the tickets information to the database
     */
    public void finishBooking() {
        if (insertDB()) {
            JOptionPane.showMessageDialog(null, "Booking success");
            moveToSearchView();
        } else {
            JOptionPane.showMessageDialog(null, "Booking not success");
        }
    }

    public void createView() {
        view = new ConfirmView(this);
        getFlightFromBooking();
        getPassengerInformation();
    }
    public Object getView() {
        if (view == null) {
            createView();
        }
        return view;
    }

    public void moveToSearchView() {
        BaseController.getInstance().changeToPanel((new SearchController().getView()));
    }

    private int rdInt(int a, int b) {
        Random random = new Random();

        while (true) {
            int result = random.nextInt() % b;
            if (result >= a) {
                return result;
            }
        }
    }

    public String getTicNumdep() {
        return ticNumDep;
    }

    public String getTicNumRe() {
        return ticNumRe;
    }


}
